import cv2
from PIL import ImageGrab
import numpy as np
import datetime
import time
import threading, queue
import math

from PySide6.QtCore import QThread, Signal


# 初始化变量
is_running = True
is_lang = 30


def generate_video():
    """
    生成录制视频
    :return:
    """
    # 当前时间戳为文件名字
    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H%M%S")
    file_name = "tmp/" + start_time + "-video"
    # file_name= input("输入录制文件的名称")
    screen = ImageGrab.grab()
    width, height = screen.size
    print(width, height)
    fource = cv2.VideoWriter_fourcc(*"XVID")
    # fource = cv2.VideoWriter_fourcc(*"mp4v")
    video = cv2.VideoWriter("%s.avi" % file_name, fource, 60, (width, height))
    for n in range(3):
        time.sleep(1)
    s = time.time()
    while True:
        im1 = ImageGrab.grab()
        im2 = cv2.cvtColor(
            np.array(im1), cv2.COLOR_RGB2BGR
        )  # cv2.COLOR_RGBA2RGB | cv2.COLOR_RGB2BGR
        video.write(im2)
        if is_running is False:
            break
        if time.time() - s > is_lang:
            break
    video.release()
    print(f"recv is onver, file:{file_name}")


class WorkerThread(QThread):
    plan = Signal(int)
    msg = Signal(str)
    state = Signal(str)
    is_running = True

    def __init__(self):
        super().__init__()
        self.piclist = queue.Queue()
        self.fps = self.hasfps()
        # self.fps = 20

    def setLang(self, out=120):
        self.lang = out

    def stop(self):
        self.is_running = False

    def hasfps(self):
        """计算单帧时长"""
        t = time.time()
        for i in range(10):
            im1 = ImageGrab.grab()
            self.piclist.put(im1)
        # return math.ceil((time.time() - t) / 10)
        return math.floor(1 / ((time.time() - t) / 10))

    def getImage(self):
        while not self.piclist:
            self.piclist.get()
        while self.is_running:
            s = time.time()
            im1 = ImageGrab.grab()
            self.piclist.put(im1)
            # e = time.time() - s
            # if e < 0.05:
            #     time.sleep(0.05 - e)

    def run(self):
        self.is_running = True
        print("当前fps:", self.fps)
        # 当前时间戳为文件名字
        start_time = datetime.datetime.now().strftime("%Y-%m-%d-%H%M%S")
        file_name = "tmp/" + start_time + "-video"
        # file_name= input("输入录制文件的名称")
        screen = ImageGrab.grab()
        width, height = screen.size

        self.state.emit("Rec")
        # 创建开始时间
        s = time.time()
        # 创建采集线程
        grab = threading.Thread(target=self.getImage)
        grab.start()
        # grab.join()
        # while not self.piclist:
        #     self.piclist.get()
        # a = 0
        # while self.is_running:
        #     im1 = ImageGrab.grab()
        #     self.piclist.put(im1)
        #     r = math.floor(time.time() - s)
        #     if not r == a:
        #         a = r
        #         self.plan.emit(self.lang - r)
        #     if r > self.lang:
        #         break

        # 计算fps
        # fps = math.floor(self.piclist.qsize() / self.lang)
        print("当前帧率", self.fps)

        # 合成
        # fource = cv2.VideoWriter_fourcc(*"XVID")
        # fource = cv2.VideoWriter_fourcc(*"MP4V")
        fource = cv2.VideoWriter_fourcc(*"X264")
        # fource = cv2.VideoWriter_fourcc(*"MP42")
        # 创建VideoWriter对象
        video = cv2.VideoWriter("%s.mp4" % file_name, fource, self.fps, (width, height))

        # 创建缩略图
        image_name = "myimage"
        img = ImageGrab.grab()
        img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
        resImg = cv2.resize(img, (640, 480))
        cv2.imwrite("%s.png" % image_name, resImg, [cv2.IMWRITE_PNG_COMPRESSION, 9])

        sum, idx, a = self.piclist.qsize(), 0, 0
        # 开始处理数据
        while True:
            if self.piclist.empty():
                if not self.is_running:
                    break
            else:
                im1 = self.piclist.get()
                im2 = cv2.cvtColor(
                    np.array(im1), cv2.COLOR_RGB2BGR
                )  # cv2.COLOR_RGBA2RGB | cv2.COLOR_RGB2BGR
                video.write(im2)
                # idx += 1
                # self.plan.emit(math.floor(idx / sum * 100))
            r = math.floor(time.time() - s)
            if not r == a:
                a = r
                self.plan.emit(self.lang - r)
            if r > self.lang:
                self.stop()
        video.release()
        grab.join()
        print(f"recv is onver, file:{file_name}")
        self.msg.emit(file_name + ".mp4")
